﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
/*
using iTextSharp.text;
using iTextSharp.text.factories;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using iTextSharp.tool.xml;
 */
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text.html.simpleparser;

namespace MalikSumLib.Utilities
{
    public class PDFManager
    {

        Document document = new Document(PageSize.A4, 80, 50, 30, 65);

        ////////////////////////////////////////////////////////
        public void ConvertFile(string FileToConvert, string OutPutFile, string FontPath)
        {
            //Microsoft.Office.Interop.Word.ApplicationClass wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();

            if (Path.GetExtension(FileToConvert).Contains("txt"))
            {
                //ConvertText(FileToConvert, OutPutFile);
                WriteDocument(FileToConvert, OutPutFile, FontPath);
            }
            else if (Path.GetExtension(FileToConvert).Contains("doc"))
            {
                word2PDF(FileToConvert, OutPutFile);
            }
            //Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
            ////doc.Path = FileToConvert;// this.Application.ActiveDocument;
            //string path = @"D:\Test\" + "NewPDF" + ".pdf";

            //doc.SaveAs(FileToConvert+ ".pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF,
            //    false, Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
            //   Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 1, 1,
            //   Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent, true, true,
            //   Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, true, true, false);
        }

        /// /////////////////////////////////////////////////


        private Microsoft.Office.Interop.Word.Application MSdoc;

        //Use for the parameter whose type are not known or say Missing
        object Unknown = Type.Missing;


        private void word2PDF(object Source, object Target)
        {
            //Creating the instance of Word Application          
            if (MSdoc == null) MSdoc = new Microsoft.Office.Interop.Word.Application();

            try
            {
                MSdoc.Visible = false;
                MSdoc.Documents.Open(ref Source, ref Unknown,
                     ref Unknown, ref Unknown, ref Unknown,
                     ref Unknown, ref Unknown, ref Unknown,
                     ref Unknown, ref Unknown, ref Unknown,
                     ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
                MSdoc.Application.Visible = false;
                MSdoc.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize;

                object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

                MSdoc.ActiveDocument.SaveAs(ref Target, ref format,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown);
            }
            catch (Exception e)
            {

            }
            finally
            {
                if (MSdoc != null)
                {
                    MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown);
                    //WordDoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown);
                }
                // for closing the application
                MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown);
            }
        }

        public void WriteDocument(string fileToConvert, string fileToWrite, string FontPath)
        {
            //Declare a itextSharp document 
            Document document = new Document();
            //Create our file stream and bind the writer to the document and the stream 
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileToWrite, FileMode.OpenOrCreate));
            //Open the document for writing 
            document.Open();
            //Add a new page 
            //document.NewPage();

            //BaseFont helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
            //==========================

            //Reference a Unicode font to be sure that the symbols are present. 
            BaseFont bfArialUniCode = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, true);
            //Create a font from the base font 
            iTextSharp.text.Font font = new iTextSharp.text.Font(bfArialUniCode, 12);

            //Use a table so that we can set the text direction 
            PdfPTable table = new PdfPTable(1);

            //Ensure that wrapping is on, otherwise Right to Left text will not display 
            //table.DefaultCell.NoWrap = false;

            //Create a cell and add text to it             
            //StreamReader streamReader = new StreamReader(documentStream, Encoding.GetEncoding("windows-1256"));
            StreamReader rdr = new StreamReader(fileToConvert, Encoding.GetEncoding("windows-1256"));// System.Text.Encoding.UTF8
            string TextToConvert = rdr.ReadToEnd();
            //Create a regex expression to detect hebrew or arabic code points 
            const string regex_match_arabic_hebrew = @"[\u0600-\u06FF,\u0590-\u05FF]+";
            if (Regex.IsMatch(TextToConvert, regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
            {
                table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            }

            //PdfPCell textCell = new PdfPCell(new Phrase(File.ReadAllText(fileToConvert), font));
            PdfPCell textCell = new PdfPCell();
            Paragraph p = new Paragraph(TextToConvert, font);
            textCell.AddElement(p);
            //Ensure that wrapping is on, otherwise Right to Left text will not display 
            //text.NoWrap = false;
            textCell.BorderWidth = 0;
            //Add the cell to the table 
            table.AddCell(textCell);
            document.Add(textCell);
            //Add the table to the document 
            document.Add(table);
            //======================

            document.Close();
            ////Launch the document if you have a file association set for PDF's 
            //Process AcrobatReader = new Process();
            //AcrobatReader.StartInfo.FileName = @"C:\Test.Pdf";
            //AcrobatReader.Start();

        }

        public void ConvertText(string TextToWrite, string FileName)
        {



            // 1- Create a Document.


            // 2- Get a PdfWriter instance.
            //PdfWriter writer = PdfWriter.GetInstance(document, new FileOutputStream(RESULT));
            PdfWriter.GetInstance(
                // that listens to the document
                document,
                // and directs a PDF-stream to a file
                new FileStream(FileName, FileMode.OpenOrCreate));
            // write sentance with different style  "samar"
            Font[] fonts = new Font[3];
            //BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
            BaseFont bfTimes = BaseFont.CreateFont(@"C:\Windows\Fonts\times.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            BaseColor bc = BaseColor.RED;
            fonts[0] = new Font(bfTimes, 12, 6, BaseColor.RED);
            fonts[1] = new Font(bfTimes, 20, 10, BaseColor.ORANGE);
            fonts[2] = new Font(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false), 12);


            // step 3: we open the document
            document.Open();

            //for (int i = 0; i < 3; i++)
            //{

            //    document.Add(new Paragraph("quick brown fox jumps over the lazy dog", fonts[i]));
            //}




            //Use a table so that we can set the text direction 
            PdfPTable table = new PdfPTable(1);

            //Create a regex expression to detect hebrew or arabic code points 
            const string regex_match_arabic_hebrew = @"[\u0600-\u06FF,\u0590-\u05FF]+";
            if (Regex.IsMatch(TextToWrite, regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
            {
                table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            }
            Font font = new Font(bfTimes, 12);
            // step 4: we add a paragraph to the document
            PdfPCell textCell = new PdfPCell(new Phrase(TextToWrite, font));
            //Ensure that wrapping is on, otherwise Right to Left text will not display 
            //text.NoWrap = false;
            textCell.BorderWidth = 0;
            //Add the cell to the table 
            table.AddCell(textCell);
            document.Add(textCell);
            //Add the table to the document 
            document.Add(table);
            //======================
            // 5- Close the Document.
            document.Close();







        }

        public void ConvertHTMLText(string TextToWrite, string FileName, string FontPath)
        {

            PdfWriter.GetInstance(document, new FileStream(FileName, FileMode.Create));
            document.Open();
            HTMLWorker htmlWorker = new HTMLWorker(document);
            //string htmlText = @"<br/> <b>this is a test </b> files in <u>html </u> ودى حاجة تانية";
            // htmlWorker.Parse(new StringReader(htmlText));


            BaseFont bfArialUniCode = BaseFont.CreateFont(FontPath,
                                            BaseFont.IDENTITY_H, true);

            PdfPTable table = new PdfPTable(1);
            //Create a regex expression to detect hebrew or arabic code points 
            const string regex_match_arabic_hebrew = @"[\u0600-\u06FF,\u0590-\u05FF]+";
            if (Regex.IsMatch(TextToWrite, regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
            {
                table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            }


            List<iTextSharp.text.IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker
                                                    .ParseToList(new System.IO.StringReader(TextToWrite), null);
            for (int k = 0; k < htmlarraylist.Count; k++)
            {
                PdfPCell textCell = new PdfPCell();
                textCell.Phrase = new Phrase();

                foreach (Chunk el in htmlarraylist[k].Chunks)
                {
                    if (el.Font.Familyname == "unknown")
                    {
                        iTextSharp.text.Font f2 = new iTextSharp.text.Font(bfArialUniCode, el.Font.Size,
                                                    el.Font.Style, el.Font.Color);
                        el.Font = f2;


                    }


                }

                textCell.Phrase.Add((IElement)htmlarraylist[k]);

                textCell.BorderWidth = 0;
                //textCell.Phrase.Add(new Phrase(10, htmlText,font));
                table.AddCell(textCell);
            }

            document.Add(table);

            document.Close();




        }
    }
}
